﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElectronicRecords.Models;
using System.Text.RegularExpressions;
using System.Web.Security;

namespace ElectronicRecords.Controllers
{
    public class SpecialistsController : Controller
    {
        //
        // GET: /Specialists/

        private DataManager _dataManager;

        public SpecialistsController(DataManager datamanager)
        {
            _dataManager = datamanager;
        }


        public ActionResult Index()
        {
            return View();
        }

        public ActionResult List()
        {
            ViewData["Title"] = "Справочник специалистов";
            ViewData["Specialists"] = _dataManager.Specialists.GetSpecialists();
            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Create()
        {

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Specialists s)
        {
            string reg = "^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$";
            Regex r = new Regex(reg);
            Match match = r.Match(s.Email);
            if (s.Firstname == null || s.Firstname.Length <= 1) ModelState.AddModelError("Firstname",
                "Фамилия должна быть более 1 символа");
            if (s.Lastname == null || s.Lastname.Length <= 1) ModelState.AddModelError("Lastname",
             "Имя должно быть более 1 символа");
            if (s.Phone == null || s.Phone.Length <= 7) ModelState.AddModelError("Phone",
              "Телефон должен быть более 6 символов");
            if (s.Email == null || s.Email.Length <= 6 || !match.Success) ModelState.AddModelError("Email",
               "Email должен быть более 5 символов");

            if (ModelState.IsValid)
            {
                //c.ID_Client = id;
                MembershipUser u = Membership.GetUser(User.Identity.Name);

                s.CreatedBy = (Guid)u.ProviderUserKey;
                
              //  _dataManager.Specialists.CreateSpecialist(s.Firstname, s.Lastname, s.Phone, s.Email);
                _dataManager.Specialists.CreateSpecialist(s);
                return RedirectToAction("List");
            }


            return View();
        }

        public ActionResult Specialist(int id)
        {
            ViewData.Model = _dataManager.Specialists.GetSpecialist(id);
            return View();
        }

        public ActionResult Delete(int id)
        {
            _dataManager.Specialists.DeleteSpecialist(id);
            return RedirectToAction("List");
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Edit(int id)
        {
            Specialists s = _dataManager.Specialists.GetSpecialist(id);
            ViewData.Model = s;

           // ViewData["Users"] = new SelectList(_dataManager.Users.GetUsers(),
           //     "ProviderUserKey", "UserName", c.CreatedBy);
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, Specialists s)
        {
            string reg = "^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$";
            Regex r = new Regex(reg);
            Match match = r.Match(s.Email);
            if (s.Firstname == null || s.Firstname.Length <= 1) ModelState.AddModelError("Firstname",
                "Фамилия должна быть более 1 символа");
            if (s.Lastname == null || s.Lastname.Length <= 1) ModelState.AddModelError("Lastname",
             "Имя должно быть более 1 символа");
            if (s.Phone == null || s.Phone.Length <= 7) ModelState.AddModelError("Phone",
              "Телефон должен быть более 6 символов");
            if (s.Email == null ||s.Email.Length <= 6 || !match.Success) ModelState.AddModelError("Email",
               "Email должен быть более 5 символов");

            if (ModelState.IsValid)
            {
                s.ID_Specialist = id;
                MembershipUser u = Membership.GetUser(User.Identity.Name);

                s.CreatedBy = (Guid)u.ProviderUserKey;
                _dataManager.Specialists.UpdateSpecialist(s);
                return RedirectToAction("List");
            }


            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Services(int id)
        {

            ViewData.Model = _dataManager.Specialists.GetServices(id);
            return View();
        }
        
        public string GetProc(int id)
        {
            string s="<form action=\"/Specialists/AddServices/"+id.ToString()
                +"\"method=\"post\">";
            s += "</br><input class=\"g-button\" type=\"submit\" value=\"Сохранить\"/></br>";
            List<Procedurs> l = _dataManager.Procedurs.GetAllProcedurs().ToList();
            IEnumerable<Procedure_Specialist_XREF> ps = _dataManager.Specialists.GetServices(id);
            bool fl=false;
            s+="<table id=\"maintable\">";
            s += "<tr><th> Добавить</th><th>Наименование процедуры</th></tr>";

            foreach (Procedurs p in l)
            {
                foreach (Procedure_Specialist_XREF psx in ps)
                {
                    if(psx.Procedurs.ID_Procedure==p.ID_Procedure) fl=true;
                }
                s += "<tr>";
                if(fl)
                s += "<td><input name=\""+p.ID_Procedure.ToString()+"\" type=\"checkbox\" value=\""+p.ID_Procedure.ToString()+ "\" checked=\"checked\"></input></td><td>"+p.Name+"</td>";
                else s += "<td><input name=\"" + p.ID_Procedure.ToString() + "\" type=\"checkbox\" value=\"" + p.ID_Procedure.ToString() + "\" ></input></td><td>"+p.Name+"</td>";
                fl=false;
                s+="</tr>";
            }
            s += "</table></br><input class=\"g-button\" type=\"submit\" value=\"Сохранить\"/></form>";
            return s;
        }

        public ActionResult AddServices(int id)
        {
            _dataManager.Specialists.RemoveAllService(id);
           
            for (int i = 0; i < Request.Form.Count; i++)
            {
                Procedure_Specialist_XREF p = new Procedure_Specialist_XREF();
                p.ID_SPECIALIST = id;
                p.ID_PROCEDURE =Convert.ToInt32(Request.Form[i]);
                MembershipUser u = Membership.GetUser(User.Identity.Name);
                p.CREATEDBY = (Guid)u.ProviderUserKey;
                _dataManager.Specialists.AddService(p);
            }
            return RedirectToAction("Services/"+id.ToString());
        }

        public ActionResult ViewShedules(int id,string date)
        {
            DateTime _date = Convert.ToDateTime(date);
            int i = (int)_date.DayOfWeek;
            DateTime beg=_date-(new TimeSpan(i-1,0,0,0));
            DateTime end = _date + (new TimeSpan(7 - i, 0, 0, 0));
            ViewData["date_begin"]=beg;
            ViewData["date_end"]=end;
                      
            ViewData["Shedules"] = _dataManager.Specialists.GetShedulesBetweenDate(id, beg, end);
           // ViewData["Shedules"] = _dataManager.Specialists.GetAllShedules(id);
            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult CreateShedules(int id)
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult CreateShedules(int id, DateTime date ,TimeSpan begin, TimeSpan end, bool is_weekly)
        {
            List<Shedules> l;
            MembershipUser u = Membership.GetUser(User.Identity.Name);
            if (is_weekly)
            {
                //определяем неделю
                l = new List<Shedules>(7);
                int i = (int)date.DayOfWeek;
                /*   l[i] = new Shedules();
                   l[i].Date_Begin = date + begin;
                   l[i].Date_End = date + end;
                   l[i].ID_Specialist=id;
                   MembershipUser u = Membership.GetUser(User.Identity.Name);
                   l[i].CreatedBy=(Guid)u.ProviderUserKey;*/
                //остальные дни
                //двигаем дату на начало недели
                date = date - (new TimeSpan(i, 0, 0, 0));
                for (int j = 0; j < 7; j++)
                {   
                    l.Add(new Shedules());
                    l[j].Date_Begin = date + begin;
                    l[j].Date_End = date + end;
                    l[j].ID_Specialist = id;
                    l[j].CreatedBy = (Guid)u.ProviderUserKey;
                    date=date.AddDays(1);
                }
            }
            else
            {
                l = new List<Shedules>(1);
                l.Add(new Shedules() { ID_Specialist=id,
                    CreatedBy=(Guid)u.ProviderUserKey,
                 Date_Begin=date+begin, Date_End=date+end});
            }

            foreach (Shedules s in l)
            {
                _dataManager.Specialists.AddShedules(s);
            }
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditShedules(int id, ViewEditShedule ss)
        {
            Shedules s = new Shedules();
            s.ID_Shedules = ss.Id;
            s.ID_Specialist = ss.spec;
            s.Date_Begin = ss.date + ss.time_begin;
            s.Date_End = ss.date + ss.time_end;
            
            if (ModelState.IsValid)
            {
                MembershipUser u = Membership.GetUser(User.Identity.Name);
                s.ID_Shedules = id;
                s.CreatedBy = (Guid)u.ProviderUserKey;
                _dataManager.Specialists.UpdateShedule(s);
                return RedirectToAction("ViewShedules/" + s.ID_Specialist.ToString(), new {date=s.Date_Begin.ToShortDateString() });
            }

            return View();
        }


        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult EditShedules(int specialist_id,int id)
        {   Shedules s=_dataManager.Specialists.GetShedule(specialist_id, id);
            ViewEditShedule vs=new ViewEditShedule();
            vs.Id=s.ID_Shedules;
            vs.spec = s.ID_Specialist;
            vs.date=s.Date_Begin-(new TimeSpan(s.Date_Begin.Hour,s.Date_Begin.Minute,0));
            vs.time_begin = s.Date_Begin-vs.date;
            vs.time_end = s.Date_End-vs.date;
            
            ViewData.Model = vs;
            return View();
        }

       


    }
}
